package com.agilya.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.Resource;

import com.agilya.dao.daointerface.ApprenantDAO;
import com.agilya.dao.exception.DAOExceptions;
import com.agilya.modele.Apprenant;
import com.sun.appserv.jdbc.DataSource;

@DAOApprenant
public class JDBCApprenantDAO implements ApprenantDAO {

	@Resource(name = "jdbc/QCMAgilya")
	private DataSource ds;

	@Override
	public boolean verifLoginApprenant(String email, String codeAcces) throws DAOExceptions {
		if (ds == null) {
			throw new DAOExceptions("Base de donnée non accessible. Data Source non initialisé");
		}

		try (Connection c = ds.getConnection(); PreparedStatement psmt = c.prepareStatement("SELECT CODE_ACCES FROM APPRENANT WHERE EMAIL = ? AND CODE_ACCES =?");) {
			psmt.setString(1, email);
			psmt.setString(2, codeAcces);

			ResultSet rs = psmt.executeQuery();

			while (rs.next()) {
				return true;

			}

		} catch (SQLException e) {
			e.printStackTrace();
			throw new DAOExceptions(e.getMessage(), e);
		}
		return false;
	}

	@Override
	public Apprenant getApprenantByEmail(String email) throws DAOExceptions {

		if (ds == null) {
			throw new DAOExceptions("Base de donnée non accessible. Data Source non initialisé");
		}

		Apprenant apprenant = null;
		try (Connection c = ds.getConnection(); PreparedStatement psmt = c.prepareStatement("SELECT * FROM APPRENANT WHERE EMAIL = ? ");) {
			psmt.setString(1, email);

			ResultSet rs = psmt.executeQuery();

			while (rs.next()) {

				int id = rs.getInt("ID_APPRENANT");
				String nom = rs.getString("NOM_APPRENANT");
				String prenom = rs.getString("PRENOM_APPRENANT");
				String societe = rs.getString("SOCIETE");
				String rue = rs.getString("RUE");
				String codepostale = rs.getString("CODEPOSTALE");
				String ville = rs.getString("VILLE");
				String telephone = rs.getString("TELEPHONE");
				String codeAcces = rs.getString("CODE_ACCES");
				boolean estActif = rs.getBoolean("APPRENANT_ESTACTIF");
				apprenant = new Apprenant(id, nom, prenom, email, societe, rue, codepostale, ville, telephone, codeAcces, estActif);

			}

		} catch (SQLException e) {

			e.printStackTrace();
			throw new DAOExceptions(e.getMessage(), e);
		}

		return apprenant;
	}

}
